package top.dj.controller;

import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import top.dj.domain.R;
import top.dj.entity.FileInfo;
import top.dj.util.FastDfsClientUtil;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

/**
 * @Author: DengJia
 * @Date: 2021/9/8 12:10
 * @Description:
 */

@RestController
@RequestMapping("/file")
public class FileController {
    @Autowired
    private FastFileStorageClient client;
    @Autowired
    private FastDfsClientUtil dfsClientUtil;

    /**
     * 文件上传
     *
     * @param file 文件
     * @return 文件信息
     */
    @PostMapping("/upload")
    public R uploadFile(@RequestParam("file") MultipartFile file) {
        FileInfo fileInfo = dfsClientUtil.uploadFile(file);
        return R.data(fileInfo);
    }


    /**
     * 文件下载
     *
     * @param uri      文件路径（不带 http://{ip}:{port}/前缀）
     * @param request  请求
     * @param response 响应
     */
    @GetMapping("/download")
    public void download(@RequestParam("filePath") String uri, HttpServletRequest request, HttpServletResponse response) {
        String group = uri.substring(0, uri.indexOf("/")); // 文件分组名称
        String path = uri.substring(uri.indexOf("/") + 1); // 文件路径
        String fileName = uri.substring(uri.lastIndexOf("/") + 1, uri.indexOf(".")); // 文件名字

        InputStream inputStream = dfsClientUtil.download(group, path);

        // 设置返回
        response.setHeader("Content-Type", request.getServletContext().getMimeType(fileName)); // 根据文件名获取MIME类型
        response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
        response.setContentType("application/json;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");

        try {
            ServletOutputStream outputStream = response.getOutputStream(); // 获取绑定了客户端的流
            IOUtils.copy(inputStream, outputStream); // 把输入流的数据写入到输出流中
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close(); // 关闭流
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 删除文件
     *
     * @param filePath 文件路径（不带 http://{ip}:{port}/前缀）
     */
    @GetMapping("/del")
    public R delFile(@RequestParam("filePath") String filePath) {
        dfsClientUtil.delFile(filePath);
        return R.ok();
    }
}
